//
//  ChangeInfoDialog.m
//  ShowHome
//
//  Created by mac on 13-7-18.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "ChangeInfoDialog.h"
#import <QuartzCore/QuartzCore.h>
#import "Utitlity.h"
#import "RoomItemModel.h"
#import "ActionPicker.h"
#import "TimingSettingViewController.h"
#import "SceneCell.h"
#import "ArmListViewCell.h"
#import "TimingSettingModel.h"

NSInteger PICKER_VIEW_ROOM_LIST_TAG = 10001;

@interface ChangeInfoDialog () <UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDataSource, UITableViewDelegate, ActionPickerDelegate>
{
    BOOL _roomChanged;
    UIPickerView *_pickertView_RoomList;
    UIPickerView *ios8Picker;
    
    RoomItemModel *_originalRoomData;//初始的room
    RoomItemModel *_currentSelectRoomData;
    NSInteger _roomDataOfListIndex;
}

@property (strong, nonatomic) ActionPicker *actionPicker;
@property (strong, nonatomic) NSArray *roomList;
@property (strong, nonatomic) NSMutableArray *scheduleList;
@property (nonatomic, weak) IBOutlet UIView *viewIconSelect;
@property (nonatomic, weak) IBOutlet UIView *viewRoomSetting;
@property (nonatomic, weak) IBOutlet UIView *viewTimingSetting;
@property (nonatomic, weak) IBOutlet UITableView *scheduleListView;
@end

@implementation ChangeInfoDialog
@synthesize scrollView;
@synthesize data;
@synthesize textName;
@synthesize cell;
@synthesize mCell;
@synthesize cCell;
@synthesize delegate;

-(void)initView
{
    self.layer.masksToBounds = YES;
    self.layer.borderWidth = 1;
    self.layer.cornerRadius = 8;
    self.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    [self setContentMode:UIViewContentModeScaleAspectFill];
    [self setClipsToBounds:YES];
    
    //icon_window_
    imgs = [NSArray arrayWithObjects:@"icon_light_",@"icon_light1_",@"icon_sensor_",@"icon_light2_",@"icon_door_",@"icon_door2_",@"icon_curtain_",@"icon_socket_",@"icon_window_pusher_",@"window_",@"icon_rolling_blind_",@"icon_garage_",@"icon_valve_",@"icon_ammeter",@"icon_camera",@"sur_0",@"sur_1",@"sur_2", @"icon_doorlock_", @"icon_alarm_", nil];
    
    int width  = [imgs count]*scrollView.frame.size.height + [imgs count]*5;
    scrollView.contentSize = CGSizeMake(width, scrollView.frame.size.height);
    
    pageShowView = [[PageShowView alloc]initWithFrame:CGRectMake(0, 0, width,  scrollView.frame.size.height)];
    [pageShowView setPics:imgs];
    [scrollView addSubview:pageShowView];
    
    _roomChanged = NO;
    
}

//!***  **/
- (void)setDeviceInfoExtraData:(NSDictionary *)dataInfo {
    
    [self setupRoom:[dataInfo[@"Room"] integerValue]];
    
    
    [self requestGetScheduleList];
    
}

- (void)setOriginalRoomData:(RoomItemModel *)roomData {

    _originalRoomData = roomData;
    [self.btnRoomSelect setTitle:_originalRoomData.roomName forState:UIControlStateNormal];
}

-(void)setData:(NSDictionary *)_data cell:(AutomationCell *)_cell
{
    self.data = _data;
    self.cell = _cell;

    PersistableInfo *info = [AutomationCell getAutoMationInfo:data];
//    int index = 0;
//    for (NSString *icon in imgs) {
//        if ([icon isEqualToString:info.icon]) {
//            break;
//        }
//        index++;
//    }
    NSInteger index = 0;
    for (; index < imgs.count; index++) {
        NSString *icon = imgs[index];
        if ([icon isEqualToString:info.icon]) {
            break;
        }
    }
    
    if (index < imgs.count ) {
        [pageShowView setCurrentPage:index];
    }

    textName.text = [self.data objectForKey:@"Alias"];
    
    int left = index * (scrollView.frame.size.height + 5);
    
    [scrollView scrollRectToVisible:CGRectMake(left, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
    
    [self setDeviceInfoExtraData:_data];
}

- (void)setupRoom:(NSInteger)roomId {
    NSInteger i = 0;
    for (RoomItemModel *roomdata in self.roomList) {

        if (roomdata.roomId == roomId) {
            [self setOriginalRoomData:roomdata];
            _roomDataOfListIndex = i;
            break;
        }
        i++;
    }

}

//meter
-(void)setMeterData:(NSDictionary *)_data cell:(MeterListCell *)_cell
{
    self.data = _data;
    self.mCell = _cell;
    
    PersistableInfo *info = [MeterListCell getMeterInfo:data];
    int index = 0;
    for (NSString *icon in imgs) {
        if ([icon isEqualToString:info.icon]) {
            break;
        }
        index++;
    }
    [pageShowView setCurrentPage:index];
    textName.text = [self.data objectForKey:@"Alias"];
    int left = index * (scrollView.frame.size.height + 5);
    
    [scrollView scrollRectToVisible:CGRectMake(left, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
    
    [self setDeviceInfoExtraData:_data];
}

//carema
-(void)setCameraData:(NSDictionary*)_data cell:(DeviceListCell*)_cell
{
    self.tag = 100;
    self.data = _data;
    self.cCell = _cell;
    
    PersistableInfo *info = [DeviceListCell getCameraInfo:data];
    int index = 0;
    for (NSString *icon in imgs) {
        if ([icon isEqualToString:info.icon]) {
            break;
        }
        index++;
    }
    [pageShowView setCurrentPage:index];
    textName.text = [self.data objectForKey:@"Alias"];
    int left = index * (scrollView.frame.size.height + 5);
    
    [scrollView scrollRectToVisible:CGRectMake(left, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];

    [self setDeviceInfoExtraData:_data];
}
//remote
- (void)setRemoteData:(NSDictionary*)_data cell:(DeviceListCell*)_cell
{
    self.tag = 200;
    self.data = _data;
    self.cCell = _cell;
    PersistableInfo *info = [DeviceListCell getRemoteInfo:data];
    int index = 0;
    for (NSString *icon in imgs) {
        if ([icon isEqualToString:info.icon]) {
            break;
        }
        index++;
    }
    [pageShowView setCurrentPage:index];
    textName.text = [self.data objectForKey:@"Alias"];
    NSLog(@"%@",info.name);
    int left = index * (scrollView.frame.size.height + 5);
    
    [scrollView scrollRectToVisible:CGRectMake(left, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
    
    [self setDeviceInfoExtraData:_data];
}

- (void)setSceneArmDData:(NSDictionary *)_data cell:(SceneArmBaseTableViewCell *)_cell{

    self.viewIconSelect.hidden = YES;
    self.viewRoomSetting.hidden = YES;
    self.viewTimingSetting.frame = self.viewIconSelect.frame;
    
    NSMutableDictionary *sceneArmData = [NSMutableDictionary dictionaryWithDictionary:_data];
    if ([_cell isMemberOfClass:[SceneCell class]]) {
        sceneArmData[@"SceneType"] = [NSNumber numberWithBool:YES];
    }else
        sceneArmData[@"ArmType"] = [NSNumber numberWithBool:YES];
    self.data = sceneArmData;
    textName.text = self.data[@"label"];
}

//- (void)setArmData:(ArmModel *)_data cell:(ArmListViewCell *)_cell {
//    
//    self.viewIconSelect.hidden = YES;
//    self.viewRoomSetting.hidden = YES;
//    self.viewTimingSetting.frame = self.viewIconSelect.frame;
//    
//    textName.text = _data.label;
//}

-(IBAction)save:(id)sender
{
    if (cell)
    {
        PersistableInfo *info = [AutomationCell getAutoMationInfo:data];
        //update name
        NSString *zid = [data objectForKey:@"ZID"];
        
        [self updateNameWithzid:zid alais:textName.text];
        
        //只能在局域修改
        ipUrl = [Utitlity judgeipUrl];
        if (ipUrl)
        {
             [data setValue:textName.text forKey:@"Alias"];
        }
        
        if (self.delegate)
        {
            [self.delegate changeDataDic:data];
        }

        info.icon = [imgs objectAtIndex:pageShowView.currentIndex];
        [info save];
        [cell updateIcon];
        
    }
    else if(mCell)
    {
        PersistableInfo *info = [MeterListCell getMeterInfo:data];
        //update name
        NSString *zid = [data objectForKey:@"ZID"];
//        [self updateNameWithzid:zid alais:textName.text];
        
        [data setValue:textName.text forKey:@"Alias"];
        ipUrl = [Utitlity judgeipUrl];
        
        if (ipUrl)
        {
            [data setValue:textName.text forKey:@"Alias"];
        }
        
        if (self.delegate)
        {
            [self.delegate changeMeterDic:data];
        }

        
        info.name = textName.text;
        info.icon = [imgs objectAtIndex:pageShowView.currentIndex];
        [info save];
        [mCell updateIcon];
    }
    else
    {
        if (self.tag == 100)
        {
            PersistableInfo *info = [DeviceListCell getCameraInfo:data];
            NSString *cid = [data objectForKey:@"CID"];
           
            ipUrl = [Utitlity judgeipUrl];
            if (ipUrl && (![info.name isEqualToString:textName.text]) )
            {
                NSString *changeAliasStr = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=4&CID=%@&Alias=%@",ipUrl,cid,textName.text];
                NSString * encodingString = [changeAliasStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSLog(@"changeAliasStr：%@",encodingString);
                
                [Utitlity commonHTTPMethod:changeAliasStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSLog(@"changeforresponseObject:%@",responseObject);
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"error:%@",error);
                }];
            
                [data setValue:textName.text forKey:@"Alias"];
            }
            
            if (self.delegate) {
                [self.delegate changeCameraDic:data];
            }
    
            info.icon = [imgs objectAtIndex:pageShowView.currentIndex];
            [info save];
            [cCell updateIcon];
        }
        else if(self.tag == 200)
        {
            PersistableInfo *info = [DeviceListCell getRemoteInfo:data];
            
            //update name
            NSString *zid = [data objectForKey:@"ZID"];
            [self updateNameWithzid:zid alais:textName.text];
            
            ipUrl = [Utitlity judgeipUrl];
            if (ipUrl)
            {
                [data setValue:textName.text forKey:@"Alias"];
            }
            
            if (self.delegate)
            {
                [self.delegate changeRemoteDic:data];
            }

            
            info.name = textName.text;
            info.icon = [imgs objectAtIndex:pageShowView.currentIndex];
            [info save];
            [cCell updateRemoteIcon];
        }
        
    }    
    
    if (_roomChanged && _originalRoomData.roomId != _currentSelectRoomData.roomId) {
        if (self.tag == 100)
            [self reqChangeCamera:data[@"CID"] toRoom:_currentSelectRoomData];
        else
            [self reqChangeToRoom:_currentSelectRoomData];
    
    }else
        [self moveToDownSide];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return NO;
}

- (void)updateNameWithzid:(NSString*)zid alais:(NSString *)alais
{    
    ipUrl = [Utitlity judgeipUrl];
    NSLog(@"ipurl:%@",ipUrl);
    if (ipUrl)
    {
        ASIFormDataRequest *formDataRequest = [ASIFormDataRequest requestWithURL:nil];
        NSString *encodedAlaismName = [formDataRequest encodeURL:alais];

        NSString *updataNameStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Set.cgi?OP=1&ID=%@&Name=%@",ipUrl,zid, encodedAlaismName];
        NSString * encodingString = [updataNameStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"encodingString:%@",encodingString);
        [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"updataNameStr responseObject:%@",responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    

}

#pragma mark - Room Select
- (void)setRoomData:(RoomItemModel *)roomData {
    
    if (_currentSelectRoomData != roomData || _currentSelectRoomData.roomId != roomData.roomId) {
        _currentSelectRoomData = roomData;
        [self.btnRoomSelect setTitle:_currentSelectRoomData.roomName forState:UIControlStateNormal];
        _roomChanged = YES;
    }
}

- (IBAction)onRoomSelectBtnClicked:(id)sender {
    
    [self doChoose:PICKER_VIEW_ROOM_LIST_TAG];
}

- (void)setRoomDataList:(NSArray *)list {
    
    RoomItemModel *roomNotConfig = [[RoomItemModel alloc] init];
    roomNotConfig.roomName = @"未分类";
    roomNotConfig.roomId = 0;
    
    NSMutableArray *arr = [NSMutableArray arrayWithObject:roomNotConfig];
    [arr addObjectsFromArray:list];
    self.roomList = arr;
}

-(void)reqChangeToRoom:(RoomItemModel *)changeRoomData {
    //更新房间
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *url = nil;
        if (changeRoomData.roomId == 0) {
            url = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_deldev&room=%ld&did=%@", ipUrl, _originalRoomData.roomId, [data objectForKey:@"ZID"]];
        }else
            url = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_adddev&room=%ld&did=%@",ipUrl, changeRoomData.roomId, [data objectForKey:@"ZID"]];
       
        [Utitlity commonHTTPMethod:url responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                if (self.delegate && [self.delegate respondsToSelector:@selector(changeInfoDialogWithData:changeToRoom:)]) {
                    
                    NSMutableDictionary *newData = [data mutableCopy];
                    newData[@"Room"] = [NSNumber numberWithLong:changeRoomData.roomId];
                    [self.delegate changeInfoDialogWithData:newData changeToRoom:_currentSelectRoomData];
                }
                [self moveToDownSide];
            }
            NSLog(@"changeforresponseObject:%@",responseObject);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            [self moveToDownSide];
        }];
    }
}

-(void)reqChangeCamera:(NSString *)cId toRoom:(RoomItemModel *)changeRoomData {
    //更新房间
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *url = nil;
        if (changeRoomData.roomId != 0) {
            url = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=5&CID=%@&Room=%ld", ipUrl, cId, changeRoomData.roomId];
        }else//从房间移除Camera
            url = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=5&CID=%@&Room=0",ipUrl, cId];
        
        [Utitlity commonHTTPMethod:url responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                if (self.delegate && [self.delegate respondsToSelector:@selector(changeInfoDialogWithData:changeToRoom:)]) {
                    
                    NSMutableDictionary *newData = [data mutableCopy];
                    newData[@"Room"] = [NSNumber numberWithLong:changeRoomData.roomId];
                    [self.delegate changeInfoDialogWithData:newData changeToRoom:_currentSelectRoomData];
                }
                [self moveToDownSide];
            }
            NSLog(@"changeforresponseObject:%@",responseObject);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            [self moveToDownSide];
        }];
    }
}

#pragma mark - UIPickerView 
-(void)doChoose:(NSInteger)viewTag
{
    if (!_pickertView_RoomList) {

        UIPickerView *pickertView = [[UIPickerView alloc] initWithFrame:CGRectZero];
        pickertView.dataSource = self;
        pickertView.delegate = self;
        pickertView.tag = viewTag;
        pickertView.showsSelectionIndicator = YES;
        _pickertView_RoomList = pickertView;
    }
    UIPickerView *picker = _pickertView_RoomList;
    
    NSInteger index = _roomDataOfListIndex;
    [_pickertView_RoomList selectRow:index inComponent:0 animated:NO];
    
    //ios 7 的自定义UIActionSheet
    if ([[UIDevice currentDevice].systemVersion floatValue] < 8)
    {
        self.actionPicker = [[ActionPicker alloc]initWithTitle:@"" delegate:self picker:picker];
        self.actionPicker.tag = viewTag;
        [self.actionPicker showInView:[UIApplication sharedApplication].keyWindow];
        
    }
    else
    {
        [self alertWithPicer:picker];
    }
}

-(void)didOKButtonPressed:(ActionPicker *)picker
{
    if (picker.tag == PICKER_VIEW_ROOM_LIST_TAG) {
        
        NSInteger picker_selected_index= [_pickertView_RoomList selectedRowInComponent:0];
        [self setRoomData:self.roomList[picker_selected_index]];
    }
}

#pragma mark - PickerView Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView1 numberOfRowsInComponent:(NSInteger)component;
{
    return self.roomList.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView1 titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    RoomItemModel *roomData = self.roomList[row];
    return roomData.roomName;
}

#pragma mark - ios UIAlertController
- (void)alertWithPicer:(UIPickerView *)picker
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:@"\n\n\n\n\n\n\n\n\n\n\n"// change UIAlertController height
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    //Make a frame for the picker & then create the picker
    CGRect pickerFrame = CGRectMake(12, 12, 270, 250);
    picker.frame = pickerFrame;
    ios8Picker = picker;
    NSLog(@"%ld",(long)ios8Picker.tag);
    
    
    //set the pickers selection indicator to true so that the user will now which one that they are chosing
    [picker setShowsSelectionIndicator:YES];
    
    //Add the picker to the alert controller
    [alert.view addSubview:picker];
    
    //make the toolbar view
    UIToolbar *toolView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, alert.view.frame.size.width-16, kToolBarHeight)];
    toolView.backgroundColor = [UIColor blackColor]; //set it's background
    toolView.barStyle = UIBarStyleBlackTranslucent;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, kToolBarHeight)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    //    titleLabel.text = title;
    UIBarButtonItem *bbtTitle = [[UIBarButtonItem alloc] initWithCustomView:titleLabel];
    UIBarButtonItem *bbtSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *bbtOK = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(OKWithPicker)];
    bbtOK.width = 60.f;
    UIBarButtonItem *bbtCancel = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(CancleWithPicker)];
    bbtCancel.width = 60.f;
    toolView.items = [NSArray arrayWithObjects:bbtCancel,bbtSpace,bbtTitle,bbtSpace,bbtOK, nil];
    
    [alert.view addSubview:toolView];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:NO completion:nil];
    
}

- (void)OKWithPicker
{
    
    [[UIApplication sharedApplication].keyWindow.rootViewController dismissModalViewControllerAnimated:YES];
}

- (void)CancleWithPicker
{
    [[UIApplication sharedApplication].keyWindow.rootViewController dismissModalViewControllerAnimated:YES];
}

#pragma mark - Timing
- (void)requestGetScheduleList {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *url = [NSString stringWithFormat:@"http://%@/cgi-bin/Schedule.cgi?action=do_get&did=%@",ipUrl, self.data[@"ZID"]];
        
        [Utitlity commonHTTPMethod:url responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                DLog(@"%@", responseObject);
                self.scheduleList = [NSMutableArray arrayWithCapacity:10];
                for (NSDictionary *item in responseObject[@"data"]) {
                    [self.scheduleList addObject:item];
                }
                [self.scheduleListView reloadData];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            
        }];
    }
    
}
- (IBAction)setTiming:(id)sender {
    
    TimingSettingViewController *vc = [[TimingSettingViewController alloc] init];
    vc.deviceData = self.data;
    vc.didSelectedBlock = ^(TimingSettingModel *model) {
        NSDictionary *dict = nil;
        if (model.type == TimingSettingDeviceTypeNormal) {
            
            NSInteger deviceCMD = 0;
            switch ([self.data[@"DeviceType"] integerValue]) {
                case SceneDeviceTypePowerMeter:
                case SceneDeviceTypeSwitch:
                    deviceCMD = 0x25;
                    break;
                case SceneDeviceTypeThermostat:
                    deviceCMD = 0x40;
                    break;
                case SceneDeviceTypeMotor:
                case SceneDeviceTypeDimmer:
                    deviceCMD = 0x26;
                    break;
                case SceneDeviceTypeDoorLock:
                    deviceCMD = 0x62;
                    break;                    
                default:
                    break;
            }
            
            if (model.runType == TimingSettingRunTypeFixedDay)
                dict = @{@"id":model.unId, @"did":self.data[@"ZID"], @"run":[NSNumber numberWithInteger:model.runType], @"type":[NSNumber numberWithInteger:model.type], @"date":[TimingSettingModel getDateTimeVal:model.date], @"cmd":[NSNumber numberWithInteger:deviceCMD], @"index":[NSNumber numberWithInteger:0], @"value":(model.deviceModel.isOn ? [NSNumber numberWithInteger:255]:[NSNumber numberWithInteger:0])};
            else
                dict = @{@"id":model.unId, @"did":self.data[@"ZID"], @"run":[NSNumber numberWithInteger:model.runType], @"type":[NSNumber numberWithInteger:model.type], @"week":@"", @"time":[model.date stringOfDateWithFormatHHmmss], @"cmd":[NSNumber numberWithInteger:deviceCMD], @"index":[NSNumber numberWithInteger:0], @"value":(model.deviceModel.isOn ? [NSNumber numberWithInteger:255]:[NSNumber numberWithInteger:0])};
                                                                                                                                                                                                                                              
        }else if (model.type == TimingSettingDeviceTypeSensorArm) {
            if (model.runType == TimingSettingRunTypeFixedDay)
                dict = @{@"id":model.unId, @"did":self.data[@"ZID"], @"run":[NSNumber numberWithInteger:model.runType], @"type":[NSNumber numberWithInteger:model.type], @"date":[TimingSettingModel getDateTimeVal:model.date], @"arm":(model.deviceModel.isOn ? @"true":@"false")};
            else
                dict = @{@"id":model.unId, @"did":self.data[@"ZID"], @"run":[NSNumber numberWithInteger:model.runType], @"type":[NSNumber numberWithInteger:model.type], @"week":model.weeks, @"time":[model.date stringOfDateWithFormatHHmmss], @"arm":(model.deviceModel.isOn ? @"true":@"false")};
        }

        if (dict) {
            [self.scheduleList addObject:dict];
            [self.scheduleListView reloadData];
        }
    };
    UINavigationController *navController = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    [navController pushViewController:vc animated:YES];
    
}

-(void)pageStart
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    UIViewController *rootVC = [[UIApplication sharedApplication] keyWindow].rootViewController;
    if ([rootVC isMemberOfClass:[UINavigationController class]]) {
        handleView = ((UINavigationController *)rootVC).topViewController.view;
    }else
        handleView = rootVC.view;
        
    keyView = self;
    [handleView addSubview:keyView];
    
    blackView = [[UIControl alloc]initWithFrame:handleView.bounds];
    blackView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5f];
    [blackView addTarget:self action:@selector(moveToDownSide) forControlEvents:UIControlEventTouchUpInside];
    [handleView insertSubview:blackView belowSubview:self];
    
    keyView.frame = CGRectMake((320-keyView.frame.size.width)/2,
                               handleView.frame.size.height,
                               keyView.frame.size.width,
                               keyView.frame.size.height);
    
    [self moveToCenterSide];
}

#pragma mark - TableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.scheduleList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cellSchedule = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cellSchedule) {
        cellSchedule = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        UISwitch *sw = [[UISwitch alloc] init];
        [sw sizeToFit];
        cellSchedule.accessoryView = sw;
    }
    
    NSString *detailText = @"";
    NSDictionary *scheduleInfo = self.scheduleList[indexPath.row];
    if ([scheduleInfo[@"run"] integerValue] == 1) {
    //"time": "15:43:00"
        cellSchedule.textLabel.text = scheduleInfo[@"time"];
        detailText = [TimingSettingModel getDescriptForWeeksVal:[scheduleInfo[@"week"] componentsSeparatedByString:@","]];
    }else {
    //"date": "20141206T154100"
        cellSchedule.textLabel.text = [TimingSettingModel getTimeFromISOString:scheduleInfo[@"date"]];
        detailText = [TimingSettingModel getDateFromISOString:scheduleInfo[@"date"]];
    }

    if ([scheduleInfo[@"type"] integerValue] == 1) {
        
        detailText = [([scheduleInfo[@"arm"] boolValue] == TRUE ? @"Arm ":@"Disarm ") stringByAppendingString:detailText];
        
    }else {
        
        NSString *value = [scheduleInfo[@"value"] integerValue] == 255 ? @"ON":@"OFF";
        detailText = [value stringByAppendingFormat:@" %@", detailText];
    }
        
    cellSchedule.detailTextLabel.text = detailText;
    cellSchedule.textLabel.font = [UIFont systemFontOfSize:18.0];
    UISwitch *sw = (UISwitch *)cellSchedule.accessoryView;
    [sw setOn:YES];
    return cellSchedule;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
    NSDictionary *model = self.scheduleList[indexPath.row];
    [self requestDeleteScheduleItem:model];
}

- (void)requestDeleteScheduleItem:(NSDictionary *)scheduleItem {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *url = [NSString stringWithFormat:@"http://%@/cgi-bin/Schedule.cgi?action=do_del&id=%@",ipUrl, scheduleItem[@"id"]];
        [Utitlity commonHTTPMethod:url responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                [self.scheduleList removeObject:scheduleItem];
                [self.scheduleListView reloadData];
            }
            NSLog(@"changeforresponseObject:%@",responseObject);
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            
        }];
    }
    
}
@end
